var app = getApp()
Component({
  lifetimes: {
    attached() {
      // 在组件实例进入页面节点树时执行
      this.getMessageList()
      wx.setNavigationBarTitle({
        title: '消息'
      })
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /* 开启全局样式设置 */
  options: {
    addGlobalClass: true,
  },

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    messageList: [],
    //当前页面
    current: 1,
    //每页的最大数
    size: 8,
    //总页面
    pages: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getMessageList: function () {
      wx.showLoading({
        title: '加载中',
      })
      var that = this;
      var messageList = this.data.messageList
      wx.request({
        url: app.host + "/message/group",
        data: {
          current: that.data.current,
          size: that.data.size
        },
        method: 'get',
        header: app.defaultHeader,
        complete(res) {
          wx.hideLoading()
          console.log(res)
          if (res.statusCode == 200) {
            if (res.data.code == 0) {
              var result = messageList.concat(res.data.data.records)
              that.setData({
                messageList: result,
                pages: res.data.data.pages,
                current: res.data.data.current
              })
            } else {
              that.setData({
                messageList: []
              })
            }
          } else {
            wx.showToast({
              title: "请求服务器失败，请检查网络!",
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    },

    getMore: function (res) {
      var current = this.data.current
      var pages = this.data.pages
      //如果当前页面小于总页面数，则加一页，再请求
      if (current < pages) {
        console.log("加载更多....")
        this.setData({
          current: current + 1
        })
        this.getMessageList();
      } else {
        console.log("没有更多数据了...")
      }

    },

    toDetail: function (e) {
      console.log(e)
      var id = e.currentTarget.dataset.sender
      wx.navigateTo({
        url: '/pages/message/detail/detail?sender=' + id,
      })
    },

    del(e) {
      console.log(e)
      var id = e.target.dataset.id
      var index = e.target.dataset.index
      //数据移除
      var messageList = this.data.messageList
      messageList.splice(index, 1)
      this.setData({
        messageList: messageList
      })
      //请求后端设置
      var that = this;
      wx.request({
        url: app.host + "/message/readStatus/" + id,
        method: 'put',
        header: app.defaultHeader,
        complete(res) {
          console.log(res)
          if (res.statusCode == 200) {
            if (res.data.code == 0) {
            } else {
            }
          } else {
          }
        }
      })
    },

  }
})